package client

import (
	"awesome-devops/applications/rpc/define"
	"awesome-devops/applications/tools"
	"fmt"
	"gitee.com/jjawesomejj/awesome-rpc/server"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"google.golang.org/grpc"
	"strconv"
	"sync"
)

var rpcMap sync.Map

type RpcClient struct {
	Host       string
	Port       int
	grpcClient *server.GrpcClient
}

func GetRpcClient(host string, port int) *RpcClient {
	uniqueId := host + "_" + strconv.Itoa(port)
	if value, ok := rpcMap.Load(uniqueId); ok {
		return value.(*RpcClient)
	}
	client := &RpcClient{
		Host: host,
		Port: port,
	}
	fmt.Println("创建了一个新的句柄")
	rpcMap.Store(uniqueId, client)
	return client
}

func (client *RpcClient) getClient() *server.GrpcClient {
	defer func() {
		if err := recover(); err != nil {
			tools.GetLogger().Error("rpcError:" + commonhelper.PrintStackTrace(err))
			return
		}
	}()
	if client.grpcClient == nil {
		client.grpcClient = &server.GrpcClient{
			Host: client.Host,
			Port: client.Port,
		}
	}
	return client.grpcClient
}

func (client *RpcClient) GetNodeService() (define.NodeServiceClient, error) {
	grpcClient := client.getClient()
	getGrpcClient, err := grpcClient.GetGrpcClient(func(conn *grpc.ClientConn) (interface{}, error) {
		return define.NewNodeServiceClient(conn), nil
	})
	if err != nil {
		return nil, err
	}
	return getGrpcClient.(define.NodeServiceClient), nil
}

func (client *RpcClient) GetRunnerService() (define.RunnerServiceClient, error) {
	grpcClient := client.getClient()
	getGrpcClient, err := grpcClient.GetGrpcClient(func(conn *grpc.ClientConn) (interface{}, error) {
		return define.NewRunnerServiceClient(conn), nil
	})
	if err != nil {
		return nil, err
	}
	return getGrpcClient.(define.RunnerServiceClient), nil
}
